//
//  Utils.m     工具类
//  PlayMusicTool
//
//  Created by 陈 宏 on 12-6-17.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "Utils.h"
#import <CommonCrypto/CommonDigest.h>
//#import "RegexKitLite.h"
#import <dirent.h>
#import <sys/stat.h>

//#import "config.h"


#define DEFAULT_VOID_COLOR [UIColor whiteColor]

//const NSString* REG_EMAIL = @"\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*";
//const NSString* REG_MOBILE = @"^(13[0-9]|15[0-9]|18[0-9])\\d{8}$";
//const NSString* REG_PHONE = @"^(([0\\+]\\d{2,3}-?)?(0\\d{2,3})-?)?(\\d{7,8})";

@implementation Utils

static Utils * _instance;

+(Utils *)sharesInstance
{
    @synchronized(self)
    {
        if (_instance==nil) {
            _instance=[[super allocWithZone:NULL] init];
        }
    }
    return _instance;
}

+(NSString *)getDefaultFilePathString:(NSString *)fileName;
{
    NSString *defaultPathString = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:fileName];
    return defaultPathString;
}

+(NSString *)getDocumentFilePathString:(NSString *)fileName;
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    return [documentsDirectory stringByAppendingPathComponent:fileName];
}

+(NSString *)getLibraryFilePathString:(NSString *)fileName;
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
    NSString *libraryDirectory = [paths objectAtIndex:0];
    return [libraryDirectory stringByAppendingPathComponent:fileName];
    
}

+(NSString *)getCacheFilePathString:(NSString *)fileName;
{
    NSArray *cache = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES); 
    NSString *cachePath = [cache objectAtIndex:0] ;
    return [cachePath stringByAppendingPathComponent:fileName];
    
}
//仅仅得到cache的路径
+(NSString *)getCachePathString;
{
    NSArray *cache = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES); 
    NSString *cachePath = [cache objectAtIndex:0] ;
    return cachePath;
}

+(NSString *)getTempPathString {
    return NSTemporaryDirectory();
}

+(NSString *)getTempFilePathString:(NSString *)fileName;
{
    return [NSTemporaryDirectory() stringByAppendingPathComponent:fileName];
}

+(NSString *)getResourceFilePathString:(NSString *) resourceName ofType:(NSString*)typeName;
{
    return [[NSBundle mainBundle] pathForResource: resourceName ofType: typeName];
}

+(void)removeFile:(NSString *)folderPath {

    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSArray *contents = [fileManager contentsOfDirectoryAtPath:folderPath error:NULL];
    NSEnumerator *enumerator = [contents objectEnumerator];
    NSString *filename;
    while ((filename = [enumerator nextObject])) {
        [fileManager removeItemAtPath:[folderPath stringByAppendingPathComponent:filename] error:NULL];
    }
}


+ (NSString *)getSaveFilePath:(NSString *)fileName
{
    NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *filePath = [documentPath stringByAppendingPathComponent:fileName];
    return filePath;
}

+ (void)saveFilePath:(NSString *)filepath fileData:(id)info andEncodeObjectKey:(NSString *)key {

    NSMutableData *data = [[NSMutableData alloc] init];
    NSKeyedArchiver *archiver= [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
    
    [archiver encodeObject:info forKey:key];
    [archiver finishEncoding];
    [data writeToFile:filepath atomically:YES];
}

+ (NSData *)loadDataFromFile:(NSString *)fileName anddencodeObjectKey:(NSString *)key {

    NSString *filePath = [Utils getSaveFilePath:fileName];

    if ([Utils isHaveFileAtPath:filePath]) {
        
        NSData *data1 = [NSData dataWithContentsOfFile:[Utils getDocumentFilePathString:fileName]];
        NSKeyedUnarchiver *archiver= [[NSKeyedUnarchiver alloc] initForReadingWithData:data1];
        id info = [archiver decodeObjectForKey:key];
        [archiver finishDecoding];
        return info;
    }
    return nil;
}

+ (NSString *)loadClientVersionKey:(NSString *)key {
    
    NSDictionary *configCenterDic = (NSDictionary *)[Utils loadDataFromFile:@"configCenter.json" anddencodeObjectKey:@"configCenter"];
    NSPredicate *bobPredicate = [NSPredicate predicateWithFormat:key];
    NSArray *configcenterArray = [[configCenterDic objectForKey:@"configCenterList"] filteredArrayUsingPredicate:bobPredicate];
    NSDictionary *legalServiceDic = [NSDictionary dictionaryWithDictionary:[configcenterArray firstObject]];
    return [legalServiceDic objectForKey:@"value"];
}

+ (BOOL)isHaveFileAtPath:(NSString *)path
{
    return [[NSFileManager defaultManager] fileExistsAtPath:path];
}

//判断文件夹是否存在
+(BOOL)judgeFileExist:(NSString * )fileName;
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString * filePath=[documentsDirectory stringByAppendingPathComponent:fileName];
    NSFileManager * fileManager=[NSFileManager defaultManager];
    return [fileManager fileExistsAtPath:filePath];
}

//去掉前后空格
+ (NSString *) getDisposalStr:(NSString *)s;
{
    if (![@"" isEqualToString:s]) {
        return [s stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    }
    return @"";
}

+(NSInteger)weiBoCountWord:(NSString*)s {
    NSUInteger i,n=[s length],l=0,a=0,b=0;
    unichar c;
    for(i=0;i<n;i++){
        c=[s characterAtIndex:i];
        if(isblank(c)){
            b++;
        }else if(isascii(c)){
            a++;
        }else{
            l++;            
        }
    }
    if(a==0 && l==0) return 0;
    return l+(int)ceilf((float)(a+b)/2.0);
}

//获取数据MD5值
+ (NSString *)md5:(NSData *)data
{
    CC_MD5_CTX md5;
    CC_MD5_Init(&md5);
    CC_MD5_Update(&md5,[data bytes],[data length]);
    unsigned char digest[CC_MD5_DIGEST_LENGTH];
    CC_MD5_Final(digest, &md5);
    
    NSString* s = [NSString stringWithFormat: @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
                   digest[0], digest[1], 
                   digest[2], digest[3],
                   digest[4], digest[5],
                   digest[6], digest[7],
                   digest[8], digest[9],
                   digest[10], digest[11],
                   digest[12], digest[13],
                   digest[14], digest[15]];
    return s;
}

//判断是否是有效的email
+(BOOL)isEmail:(NSString *)input{
//    return [input isMatchedByRegex:@"\\b([a-zA-Z0-9%_.+\\-]+)@([a-zA-Z0-9.\\-]+?\\.[a-zA-Z]{2,6})\\b"];
    NSString *emailRegex = @"^([a-zA-Z0-9]*[-_]?[a-zA-Z0-9]+)*@([a-zA-Z0-9]*[-_]?[a-zA-Z0-9]+)+[\\.][A-Za-z]{2,3}([\\.][A-Za-z]{2})?$";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:input];
    return YES;
}

+(BOOL)isMobileNum:(NSString *)input{
//    BOOL rs = YES;
//    if ([input length] != 11) {
//        return NO;
//    }
//    if (![Utils isNumber:input]) {
//        return NO;
//    }
//    for (int i = 0; i < [input length]; ++i) {
//        unichar c = [input characterAtIndex:i];
//        if (c > 47 && c < 58) {
//            
//        }else
//        {
//            return NO;
//        }
//        if (i == 0 &&  c != '1') {
//            rs = NO;
//            break;
//        }
//    }
//	return rs;
    NSString * MOBILE = @"^((13[0-9])|(15[^4,\\D])|(18[0,3,5-9]))\\d{8}$";
    NSString * CM = @"^1(34[0-8]|(3[5-9]|5[017-9]|8[278])\\d)\\d{7}$";
    
    NSString * CU = @"^1(3[0-2]|5[256]|8[56])\\d{8}$";
    
    NSString * CT = @"^1((33|53|8[09])[0-9]|349)\\d{7}$";
    
    // NSString * PHS = @"^0(10|2[0-5789]|\\d{3})\\d{7,8}$";
    
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
    NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
    NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
    BOOL res1 = [regextestmobile evaluateWithObject:input];
    BOOL res2 = [regextestcm evaluateWithObject:input];
    BOOL res3 = [regextestcu evaluateWithObject:input];
    BOOL res4 = [regextestct evaluateWithObject:input];
    
    if (res1 || res2 || res3 || res4 )
    {
        return YES;
    }
    else
    {
        return NO;
    }
}

+(BOOL)isIdentityCardNo:(NSString *)input {
    NSString *emailRegex = @"\\d{15}|(\\d{17}([0-9]|X|x)$)";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:input];
}
+(BOOL)isYouBian:(NSString *)input
{
    
    NSString *emailRegex = @"[1-9]\\d{5}(?!\\d)";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:input];
}
+(BOOL)isNumber:(NSString *)input {
    NSString *emailRegex = @"^\\-?([1-9]\\d*|0)(\\.\\d{0,2})?$";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    BOOL isMatch =[emailTest evaluateWithObject:input];
    return isMatch;
}

+ (NSString *)millisecondConvertedToDay:(unsigned long long )time {
    
    NSDate *date = [[NSDate alloc]initWithTimeIntervalSince1970:time/1000.0];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    return [dateFormatter stringFromDate:date];
}

+ (NSString *)millisecondToDateByFormatter:(unsigned long long)time formattter:(NSString * ) format {
    
    if (format==nil||[format isEqualToString:@""]) {
        format=@"yyyy-MM-dd HH:mm:ss";
    }
    NSDate *date = [[NSDate alloc]initWithTimeIntervalSince1970:time/1000.0];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat = format;
    return [dateFormatter stringFromDate:date];
}

+ (NSString *)secondToDateByFormatter:(unsigned long long)time formattter:(NSString * ) format {
    if (format==nil||[format isEqualToString:@""]) {
        format=@"yyyy-MM-dd HH:mm:ss";
    }
    NSDate *date = [[NSDate alloc]initWithTimeIntervalSince1970:time];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat = format;
    return [dateFormatter stringFromDate:date];
}

+ (NSString *)translateDateString:(NSString *)translateDateString format:(NSString *)format toFormat:(NSString *)tofarmt {
    if (translateDateString==nil || format==nil || tofarmt == nil) {
        return @"";
    }
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:format];
    NSDate *translateDate = [dateFormatter dateFromString:translateDateString];
    
    NSDateFormatter *translateDateFormatter = [[NSDateFormatter alloc] init];
    [translateDateFormatter setDateFormat:tofarmt];
    NSString *string = [translateDateFormatter stringFromDate:translateDate];
    
    return string;
}

//+ (NSString *)getWeekdayFromDate:(NSString *)dateStr formatter:(NSString *)matter {
//
//    NSCalendar* calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
//    
//    NSDateComponents* components = [[NSDateComponents alloc] init];
//   
//    NSInteger unitFlags = NSYearCalendarUnit |
//   
//                             NSMonthCalendarUnit |
//    
//                            NSDayCalendarUnit |
//   
//                            NSWeekdayCalendarUnit |
//   
//                            NSHourCalendarUnit |
// 
//                          NSMinuteCalendarUnit |
//  
//                            NSSecondCalendarUnit;
//    
//    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
//    [formatter setDateFormat:matter];
//    NSDate *date = [formatter dateFromString:dateStr];
//   
//    if (date == nil) {
//        return @"";
//    }
//    components = [calendar components:unitFlags fromDate:date];
// 
//    NSUInteger weekday = [components weekday];
//    
//    switch (weekday) {
//        case 1:
//            return @"星期天";
//            break;
//        case 2:
//            return @"星期一";
//            break;
//        case 3:
//            return @"星期二";
//            break;
//        case 4:
//            return @"星期三";
//            break;
//        case 5:
//            return @"星期四";
//            break;
//        case 6:
//            return @"星期五";
//            break;
//        case 7:
//            return @"星期六";
//            break;
//        default:
//            return @"";
//            break;
//    }
//    return @"";
//}

+ (UIImage *)fixOrientation:(UIImage *)aImage {
    // No-op if the orientation is already correct
    if (aImage.imageOrientation == UIImageOrientationUp)
        return aImage;
    
    // We need to calculate the proper transformation to make the image upright.
    // We do it in 2 steps: Rotate if Left/Right/Down, and then flip if Mirrored.
    CGAffineTransform transform = CGAffineTransformIdentity;
    
    switch (aImage.imageOrientation) {
        case UIImageOrientationDown:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, aImage.size.height);
            transform = CGAffineTransformRotate(transform, M_PI);
            break;
            
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
            transform = CGAffineTransformRotate(transform, M_PI_2);
            break;
            
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, 0, aImage.size.height);
            transform = CGAffineTransformRotate(transform, -M_PI_2);
            break;
        default:
            break;
    }
    
    switch (aImage.imageOrientation) {
        case UIImageOrientationUpMirrored:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
            
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.height, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
        default:
            break;
    }
    
    // Now we draw the underlying CGImage into a new context, applying the transform
    // calculated above.
    CGContextRef ctx = CGBitmapContextCreate(NULL, aImage.size.width, aImage.size.height,
                                             CGImageGetBitsPerComponent(aImage.CGImage), 0,
                                             CGImageGetColorSpace(aImage.CGImage),
                                             CGImageGetBitmapInfo(aImage.CGImage));
    CGContextConcatCTM(ctx, transform);
    switch (aImage.imageOrientation) {
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            // Grr...
            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.height,aImage.size.width), aImage.CGImage);
            break;
            
        default:
            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.width,aImage.size.height), aImage.CGImage);
            break;
    }
    
    // And now we just create a new UIImage from the drawing context
    CGImageRef cgimg = CGBitmapContextCreateImage(ctx);
    UIImage *img = [UIImage imageWithCGImage:cgimg];
    CGContextRelease(ctx);
    CGImageRelease(cgimg);
    return img;
}

+(UIImage*)scaleToSize:(UIImage*)img size:(CGSize)size
{
    // 创建一个bitmap的context
    // 并把它设置成为当前正在使用的context
    UIGraphicsBeginImageContext(size);
    
    // 绘制改变大小的图片
    [img drawInRect:CGRectMake(0, 0, size.width, size.height)];
    
    // 从当前context中创建一个改变大小后的图片
    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    
    // 使当前的context出堆栈
    UIGraphicsEndImageContext();
    
    
    // 返回新的改变大小后的图片
    return scaledImage;
}


+(NSString *)ToHex:(long long int)tmpid
{
    //    NSString *endtmp=@"";
    NSString *nLetterValue;
    //    NSString *nStrat;
    NSString *str =@"";
    //    tmpid = 13621631651;
    long long int ttmpig;
    
    
    
    for (int i = 0; i<9; i++) {
        
        
        ttmpig=tmpid%16;
        
        tmpid=tmpid/16;
        switch (ttmpig)
        {
            case 10:
                nLetterValue =@"A";break;
            case 11:
                nLetterValue =@"B";break;
            case 12:
                nLetterValue =@"C";break;
            case 13:
                nLetterValue =@"D";break;
            case 14:
                nLetterValue =@"E";break;
            case 15:
                nLetterValue =@"F";break;
            default:nLetterValue=[[NSString alloc]initWithFormat:@"%lli",ttmpig];
                
        }
        str = [nLetterValue stringByAppendingString:str];
        if (tmpid == 0) {
            break;
        }
        
    }
    
    //        } while (tmpid == 0);
    //
    return str;
}


//字符串转颜色
+ (UIColor *) colorWithHexString: (NSString *) stringToConvert
{
    NSString *cString = [[stringToConvert stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    
    
    if ([cString length] < 6)
        return DEFAULT_VOID_COLOR;
    if ([cString hasPrefix:@"#"])
        cString = [cString substringFromIndex:1];
    if ([cString length] != 6)
        return DEFAULT_VOID_COLOR;
    
    NSRange range;
    range.location = 0;
    range.length = 2;
    NSString *rString = [cString substringWithRange:range];
    
    range.location = 2;
    NSString *gString = [cString substringWithRange:range];
    
    range.location = 4;
    NSString *bString = [cString substringWithRange:range];
    
    
    unsigned int r, g, b;
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];
    
    return [UIColor colorWithRed:((float) r / 255.0f)
                           green:((float) g / 255.0f)
                            blue:((float) b / 255.0f)
                           alpha:1.0f];
}

//得到日期开始和结束时间
+(NSArray *)getStartDayAndEndDay:(TimeStateType)type{
    NSDate *today = [NSDate date];
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *dayComponents = [gregorian components:(NSDayCalendarUnit | NSWeekdayCalendarUnit|NSMonthCalendarUnit|kCFCalendarUnitYear) fromDate:today];

    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSMutableArray *temp = [NSMutableArray arrayWithCapacity:0];
    if (type==WeekType) {
        NSInteger weekday = [dayComponents weekday];
        NSInteger week = [dayComponents week];
        NSLog(@"week :%ld",(long)week);
        NSDate *startDate = [[NSDate alloc] initWithTimeIntervalSinceNow:-weekday*60*60*24];
        NSString *startString = [formatter stringFromDate:startDate];
        
        for(int i = 1;i<5;i++){
            NSDate *endDate = [NSDate dateWithTimeInterval:-(7*i*60*60*24) sinceDate:startDate];
            NSString *endString = [formatter stringFromDate:endDate];
            startString = [startString stringByReplacingOccurrencesOfString:@"-" withString:@"."];
            endString = [endString stringByReplacingOccurrencesOfString:@"-" withString:@"."];
            [temp addObject:[NSString stringWithFormat:@"%@-%@",endString,startString]];
            startString = endString;
            startDate = endDate;
        }
    }else if(type==MonthType){
        NSInteger month  =  [dayComponents month];
        NSInteger year= [dayComponents year];
        for (int i=1; i<5; i++) {
            if (month==1) {
                year--;
            }
            month = month==1?12:month-1;
            
            dayComponents.day = 1;
            dayComponents.year=year;
            dayComponents.month = month;
            NSRange range = [gregorian rangeOfUnit:NSDayCalendarUnit
                                            inUnit:NSMonthCalendarUnit
                                           forDate:[gregorian dateFromComponents:dayComponents]];
            NSDate *firstDate = [gregorian dateFromComponents:dayComponents];
            [dayComponents setDay:range.length];
            NSDate *lastDate = [gregorian dateFromComponents:dayComponents];
            NSString *startString = [formatter stringFromDate:firstDate];
            NSString *endString = [formatter stringFromDate:lastDate];
            startString = [startString stringByReplacingOccurrencesOfString:@"-" withString:@"."];
            endString = [endString stringByReplacingOccurrencesOfString:@"-" withString:@"."];
            [temp addObject:[NSString stringWithFormat:@"%@-%@",startString,endString]];
        }
        
        
    }

return temp;
}


+(long long) fileSizeAtPath:(NSString*) filePath
{
    NSFileManager* manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:filePath]){
        return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
    }
    return 0;
}


//获取文件夹大小
+(long long)folderSize:(const char *)folderPath {
    long long folderSize = 0;
    DIR* dir = opendir(folderPath);
    if (dir == NULL) {
        return 0;
    }
    struct dirent* child;
    while ((child = readdir(dir)) != NULL) {
        if (child->d_type == DT_DIR
            && (child->d_name[0] == '.' && child->d_name[1] == 0)) {
            continue;
        }
        
        if (child->d_type == DT_DIR
            && (child->d_name[0] == '.' && child->d_name[1] == '.' && child->d_name[2] == 0)) {
            continue;
        }
        
        NSUInteger folderPathLength = strlen(folderPath);
        char childPath[1024];
        stpcpy(childPath, folderPath);
        if (folderPath[folderPathLength - 1] != '/'){
            childPath[folderPathLength] = '/';
            folderPathLength++;
        }
        
        stpcpy(childPath + folderPathLength, child->d_name);
        childPath[folderPathLength + child->d_namlen] = 0;
        if (child->d_type == DT_DIR){
            folderSize += [self folderSize:childPath];
            struct stat st;
            if (lstat(childPath, &st) == 0) {
                folderSize += st.st_size;
            }
        } else if (child->d_type == DT_REG || child->d_type == DT_LNK){
            struct stat st;
            if (lstat(childPath, &st) == 0) {
                folderSize += st.st_size;
            }
        }
    }
    
    return folderSize;
}


// 计算字符串的高度
+ (CGFloat)heightForString:(NSString *)string fontSize:(float)fontSize andWidth:(float)width
{
    if (string==nil) {
        return 0;
    }
    if (IOS7) {
        if ((NSNull *)string == [NSNull null]) {
            return 0;
        }
        if (string!=nil && string.length>=1) {
            UIFont * tfont = [UIFont systemFontOfSize:fontSize];
            CGSize size = CGSizeMake(width,CGFLOAT_MAX);
            NSDictionary * tdic = [NSDictionary dictionaryWithObjectsAndKeys:tfont,NSFontAttributeName,nil];
            CGSize  actualsize =[string boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin  attributes:tdic context:nil].size;
            return actualsize.height;
        }
        return 0;

    }
    else {
        if (string!=nil && string.length>1) {
            CGSize sizeToFit = [string sizeWithFont:[UIFont systemFontOfSize:fontSize] constrainedToSize:CGSizeMake(width, CGFLOAT_MAX) lineBreakMode:NSLineBreakByWordWrapping];//此处的换行类型（lineBreakMode）可根据自己的实际情况进行设置
            return sizeToFit.height;
        }
        return 0;
    }
    
}

// 计算字符串长度
+ (CGFloat)widthForString:(NSString *)string fontSize:(float)fontSize andHeight:(float)height
{
    if (string==nil) {
        return 0;
    }
    if (IOS7) {
        UIFont * tfont = [UIFont systemFontOfSize:fontSize];
        CGSize size = CGSizeMake(CGFLOAT_MAX,height);
        NSDictionary * tdic = [NSDictionary dictionaryWithObjectsAndKeys:tfont,NSFontAttributeName,nil];
        CGSize  actualsize =[string boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin  attributes:tdic context:nil].size;
        return actualsize.width;
    }
    else {
        CGSize sizeToFit = [string sizeWithFont:[UIFont systemFontOfSize:fontSize] constrainedToSize:CGSizeMake(CGFLOAT_MAX, height) lineBreakMode:NSLineBreakByWordWrapping];//此处的换行类型（lineBreakMode）可根据自己的实际情况进行设置
        return sizeToFit.width;
    }
}

+ (NSString *)translateToCardString:(NSString *)string interval:(NSInteger)interval
{
    if (!string) {
        return @"";
    }
    NSMutableString *translateStr = [NSMutableString stringWithString:string];
    
    NSInteger tempNum = 0;
    for (int i = 0; i < string.length; i++) {
        
        if (i%interval==0 && i>0) {
            ///插入空格
            [translateStr insertString:@" " atIndex:i+tempNum];
            tempNum++;
        }
    }
    return translateStr;
}
+(NSMutableAttributedString *)changeStringColor:(NSString*)totleStr changeStr:(NSString *)changeStr changeColor:(UIColor *)changeColor changeFont:(CGFloat)changeFontSize
{
    NSMutableAttributedString *registerStr = [[NSMutableAttributedString alloc] initWithString:totleStr];
    
    NSRange range1 = [totleStr rangeOfString:changeStr];
    [registerStr setAttributes:@{NSForegroundColorAttributeName:changeColor,
                                 NSFontAttributeName:[UIFont systemFontOfSize:changeFontSize]}
                         range:range1];
    
    return registerStr;
}
+ (NSAttributedString *)getDifferentColorString:(NSString *)totalStr oneStr:(NSString *)oneStr color:(UIColor *)oneColor otherStr:(NSString *)otherStr ortherColor:(UIColor *)otherColor changeFont:(CGFloat)size{

    NSMutableAttributedString *registerStr = [[NSMutableAttributedString alloc] initWithString:totalStr];
    if (oneStr) {
        NSRange range1 = [totalStr rangeOfString:oneStr];
        [registerStr setAttributes:@{NSForegroundColorAttributeName:oneColor,
                                     NSFontAttributeName:[UIFont systemFontOfSize:size]}
                             range:range1];
    }
    if (otherStr) {
        NSRange range2 = [totalStr rangeOfString:otherStr];
        
        [registerStr setAttributes:@{NSForegroundColorAttributeName:otherColor,
                                     NSFontAttributeName:[UIFont systemFontOfSize:size]}
                             range:range2];
    }

    return registerStr;
}

+ (NSAttributedString *)getDifferentFontString:(NSString *)totalStr oneStr:(NSString *)oneStr font:(UIFont *)oneFont color:(UIColor *)oneColor otherStr:(NSString *)otherStr ortherFont:(UIFont *)otherFont ortherColor:(UIColor *)otherColor {
    NSMutableAttributedString *registerStr = [[NSMutableAttributedString alloc] initWithString:totalStr];
    if (oneStr) {
        NSRange range1 = NSMakeRange(0, oneStr.length);
        [registerStr setAttributes:@{NSForegroundColorAttributeName:oneColor,
                                     NSFontAttributeName:oneFont}
                             range:range1];
    }
    if (otherStr) {
        NSRange range2 = NSMakeRange(oneStr.length, otherStr.length);
        
        [registerStr setAttributes:@{NSForegroundColorAttributeName:otherColor,
                                     NSFontAttributeName:otherFont}
                             range:range2];
    }
    
    return registerStr;
}

+ (NSMutableAttributedString *)getLineSpaceString:(NSString *)string lineSpace:(CGFloat)space alignment:(NSTextAlignment)alignment {
    
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:string];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setLineSpacing:space];//调整行间距
    paragraphStyle.alignment = alignment;
    [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [string length])];
    return attributedString;
}

+ (NSString *)getBankName:(NSString *)bankCode {
    
    NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"BankLogoList" ofType:@"plist"];
    NSMutableDictionary *bankDic = [[NSMutableDictionary alloc] initWithContentsOfFile:plistPath];
    NSDictionary *bankInfo = [bankDic objectForKey:bankCode];
    
    if (bankInfo==nil) {
        return @"";
    }
    return [bankInfo objectForKey:@"name"];
    
}

+ (NSString *)getBankLogo:(NSString *)bankCode {
    
    NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"BankLogoList" ofType:@"plist"];
    NSMutableDictionary *bankDic = [[NSMutableDictionary alloc] initWithContentsOfFile:plistPath];
    NSDictionary *bankInfo = [bankDic objectForKey:bankCode];
    
    if (bankInfo==nil) {
        return @"";
    }
    return [bankInfo objectForKey:@"logo"];
    
}

+ (NSString *)getBankCardType:(NSString *)bankCardtype {
    
    NSDictionary *bankCardTypeDic = @{@"00": @"未知",
                          @"01": @"借记账户",
                          @"02": @"贷记账户",
                          @"03": @"准贷记账户",
                          @"04": @"借贷合一账户",
                          @"05": @"预付费账户",
                          @"06": @"半开放预付费账户"};
    NSString *temp = [bankCardTypeDic objectForKey:bankCardtype];
    return temp==nil?@"":temp;
}

+ (NSString *)stringByInfoArray:(NSArray *)array stepetorStr:(NSString *)str {
    
    NSString *tempStr = [NSString string];
    for (int i = 0; i < array.count; i++) {
        NSString *string = array[i];
        if (string&&string.length>0) {
            if (i!=0) {
                tempStr = [tempStr stringByAppendingString:str];
            }
            tempStr = [tempStr stringByAppendingString:string];
        }
    }
    return tempStr;
}

+ (NSString *)stringByStepetorStr:(NSString *)str andInfo:(NSString *)info, ... {
    
    NSString *tempStr = [NSString string];

    
    va_list args;
    va_start(args, info);

    NSUInteger i = 0;
    NSString *otherString;
    if (info&&info.length>0) {
        tempStr = [tempStr stringByAppendingString:info];
        i = 1;
    }
    while ((otherString = va_arg(args, NSString *)))
    {
        //依次取得所有参数
        if (otherString&&otherString.length>0) {
            if (i!=0) {
                tempStr = [tempStr stringByAppendingString:str];
            }
            tempStr = [tempStr stringByAppendingString:otherString];
            i++;

        }
    }

    va_end(args);
    
    return tempStr;
}

+ (UILabel *)lineLabelWithFrame:(CGRect)frame color:(UIColor *)color {
    UILabel *lineLabel = [[UILabel alloc] init];
    lineLabel.backgroundColor = color;
    lineLabel.frame = CGRectMake(frame.origin.x, frame.origin.y, frame.size.width, 0.5);
    
    return lineLabel;
}

+ (NSMutableAttributedString *)setTextColor:(UIColor *)textColor  withRange:(NSRange)textRange withString:(NSString *)string
{
    NSMutableAttributedString *mutableString =[[NSMutableAttributedString alloc] initWithString:string];
    [mutableString addAttribute:NSForegroundColorAttributeName value:textColor range:textRange];
    return mutableString;
}

///**
// 获取系统设备ip
// **/
//+ (NSString *)getDeviceIp;
//{
//    char iphone_ip[255];
//    strcpy(iphone_ip,"127.0.0.1"); // if everything fails
//    NSHost* myhost =[NSHost currentHost];
//    if (myhost)
//    {
//        NSString *ad = [myhost address];   
//        if (ad)
//            strcpy(iphone_ip,[ad cStringUsingEncoding:NSASCIIStringEncoding]);
//    }
//    return [NSString stringWithFormat:@"%s",iphone_ip];
//}


#pragma mark- 拨打电话
+(void)callPeopleBy:(NSString*)call view:(UIView*)view
{
    UIWebView*callWebview =[[UIWebView alloc] init];
    
    NSString *telUrl = [NSString stringWithFormat:@"tel:%@",call];
    
    NSURL *telURL =[NSURL URLWithString:telUrl];// 貌似tel:// 或者 tel: 都行
    
    [callWebview loadRequest:[NSURLRequest requestWithURL:telURL]];
    
    //记得添加到view上
    
    [view addSubview:callWebview];
}
#pragma mark-  判断是否包含特殊符号
+(BOOL)checkSepcial:(NSString*)str
{
    NSString *checkPsw=@"[`~!@#$%^&*()+=|{}':;',//[//].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", checkPsw];
    BOOL res1 = [regextestmobile evaluateWithObject:str];
    if (res1) {
        return YES;
    }
    else
    {
        return NO;
    }
    
}
#pragma mark- 改变字符串多处颜色
+(NSMutableAttributedString*)theTotleStr:(NSString*)totleString changedString:(NSArray*)changeArr colorArr:(NSArray*)colorArr  font:(UIFont*)font
{
    
    NSString *substr=totleString;
    NSMutableArray *mrang=[[NSMutableArray alloc]init];
    NSRange oldRange=NSMakeRange(0, 0);
    for (int i=0; i<changeArr.count; i++) {
        NSRange range= [substr rangeOfString:[changeArr objectAtIndex:i]];
        
        substr=[substr substringToIndex:range.length+range.location];
        [mrang addObject:substr];
        
        substr=[totleString substringFromIndex:oldRange.location+oldRange.length+range.length+range.location];
        
        oldRange=range;
        
    }
    NSMutableAttributedString *mstr=[[NSMutableAttributedString alloc]init];
    for (int i=0; i<mrang.count; i++) {
        NSMutableAttributedString *m=[[NSMutableAttributedString alloc]initWithString:[mrang objectAtIndex:i]];
        NSString *changestr=[mrang objectAtIndex:i];
        NSRange range=[changestr rangeOfString:[changeArr objectAtIndex:i]];
        [m setAttributes:@{NSForegroundColorAttributeName:[colorArr objectAtIndex:i],NSFontAttributeName:font} range:range];
        [mstr appendAttributedString:m];
    }
    return mstr;
}

/** 判断当前输入的是不是数字*/
+ (BOOL)isNumberInTextField:(UITextField *)startPriceTextField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    BOOL isHaveDian = NO;
    if ([startPriceTextField.text rangeOfString:@"."].location==NSNotFound) {
        isHaveDian=NO;
    }else {
        isHaveDian = YES;
    }
    if ([string length]>0)
    {
        unichar single=[string characterAtIndex:0];//当前输入的字符
        if ((single >='0' && single<='9') || single=='.')//数据格式正确
        {
            //首字母不能为0和小数点
            if([startPriceTextField.text length]==0){
                if(single == '.'){
                    [self showMess:@"亲，第一个数字不能为小数点"];
                    [startPriceTextField.text stringByReplacingCharactersInRange:range withString:@""];
                    return NO;
                    
                }
                if (startPriceTextField.text.length>=2) {
                    unichar single2=[startPriceTextField.text characterAtIndex:1];
                    if (single2 != '.' && single == '0'){
                        [self showMess:@"亲，您输入的格式不正确"];
                        return NO;
                    }
                }
            }
            if (single=='.')
            {
                if(!isHaveDian)//text中还没有小数点
                {
                    isHaveDian=YES;
                    return YES;
                }else
                {
                    [self showMess:@"亲，您已经输入过小数点了"];
                    [startPriceTextField.text stringByReplacingCharactersInRange:range withString:@""];
                    return NO;
                }
            }
            else
            {
                if (isHaveDian)//存在小数点
                {
                    //判断小数点的位数
                    NSRange ran=[startPriceTextField.text rangeOfString:@"."];
                    NSInteger tt=range.location-ran.location;
                    if (tt <= 2){
                        return YES;
                    }else{
                        [self showMess:@"亲，您最多输入两位小数"];
                        return NO;
                    }
                }
                else
                {
                    if (startPriceTextField.text.length==1) {
                        unichar single2=[startPriceTextField.text characterAtIndex:0];
                        if (single != '.' && single2 == '0'){
                            [self showMess:@"亲，您输入的格式不正确"];
                            return NO;
                        }
                    }
                    return YES;
                }
            }
        }else{//输入的数据格式不正确
            [self showMess:@"亲，您输入的格式不正确"];
            [startPriceTextField.text stringByReplacingCharactersInRange:range withString:@""];
            return NO;
        }
    }
    else
    {
        return YES;
    }
}
+ (void) showMess:(NSString *)mess {
//    [[RemindView share] show];
//    [[RemindView share] showToView:[UIApplication sharedApplication].keyWindow withMess:mess hidentAfter:1];
}
/**
 *计算字符串字数
 */
+ (int)stringCountWord:(NSString*)str{
    int i,l=0,a=0,b=0;
    NSInteger n = [str length];
    unichar c;
    for(i=0;i<n;i++){
        c=[str characterAtIndex:i];
        if(isblank(c)){
            b++;
        }else if(isascii(c)){
            a++;
        }else{
            l++;
        }
    }
    if(a==0 && l==0) return 0;
    return l+(int)ceilf((float)(a+b)/2.0);
}
+ (NSString *)stringAtCount:(int)count string:(NSString *)str {
    int i,l=0,a=0,b=0;
    NSInteger n = [str length];
    unichar c;
    for(i=0;i<n;i++){
        c=[str characterAtIndex:i];
        if(isblank(c)){
            b++;
        }else if(isascii(c)){
            a++;
        }else{
            l++;
        }
        int currentCount = l+(int)ceilf((float)(a+b)/2.0);
        if (currentCount == count) {
            return [str substringWithRange:NSMakeRange(0, currentCount)];
        }
        
    }
    return str;
//    if(a==0 && l==0) return 0;
//    return l+(int)ceilf((float)(a+b)/2.0);
}
//身份证号
+ (BOOL) validateIdentityCard: (NSString *)identityCard
{
    BOOL flag;
    if (identityCard.length <= 0) {
        flag = NO;
        return flag;
    }
    NSString *regex2 = @"^(\\d{14}|\\d{17})(\\d|[xX])$";
    NSPredicate *identityCardPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex2];
    return [identityCardPredicate evaluateWithObject:identityCard];
}
+ (NSString*)md5SignStr {
    //测试公钥：BD737FCC5ECB42FE83FC
    //正式公钥：13734F73789A43C6B5DE
    NSString *inPutText = [NSString stringWithFormat:@"%@%@",@"BD737FCC5ECB42FE83FC",@"@NOTLOGIN4558965222545"];
    if ([AppData share].doLogin) {
        inPutText = [NSString stringWithFormat:@"%@%@",@"BD737FCC5ECB42FE83FC",[AppData share].username];
    }
    
    const char *cStr = [inPutText UTF8String];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(cStr, (CC_LONG)strlen(cStr), result);
    
    return [[NSString stringWithFormat:@"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
             result[0], result[1], result[2], result[3],
             result[4], result[5], result[6], result[7],
             result[8], result[9], result[10], result[11],
             result[12], result[13], result[14], result[15]
             ] lowercaseString];
}
#pragma mark - url转码解码
+ (NSString*)URLDecodedString:(NSString *)str
{
    NSString *result = (__bridge_transfer NSString *)CFURLCreateStringByReplacingPercentEscapesUsingEncoding(kCFAllocatorDefault,(CFStringRef)str,CFSTR(""),kCFStringEncodingUTF8);
    if(result)
        return result;
    return @"";
}
+ (NSString *)URLEncodedString:(NSString *)str
{
    NSString *result = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,(CFStringRef)str,NULL,CFSTR(":/?#[]@!$ &'()*+,;=\"<>%{}|\\^~`"),kCFStringEncodingUTF8));
    if(result)
        return result;
    return @"";
}
@end
